/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.infrastructure.adapters;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itgrail.pilot.domain.user.entity.KeyResultE;
import com.itgrail.pilot.domain.user.ports.KeyResultPort;
import com.itgrail.pilot.infrastructure.converter.KeyResultConverter;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.KeyResultMapper;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.KeyResultDO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.itgrail.grail.ddd.annotation.infrastructure.Adapter;

import java.util.List;


@Adapter
public class KeyResultAdapter implements KeyResultPort {

    @Autowired
    private KeyResultMapper mapper;

    @Autowired
    private KeyResultConverter converter;


    @Override
    public int add(KeyResultE keyResultE) {
        KeyResultDO keyResultDO = converter.entityToData(keyResultE);
        return mapper.insert(keyResultDO);
    }

    @Override
    public int update(KeyResultE keyResultE) {
        KeyResultDO keyResultDO = converter.entityToData(keyResultE);
        return mapper.updateById(keyResultDO);
    }

    @Override
    public int delete(KeyResultE keyResultE) {
        KeyResultDO keyResultDO = converter.entityToData(keyResultE);
        return mapper.updateById(keyResultDO);
    }

    @Override
    public void deleteByObjectiveId(Integer objectiveId) {
        QueryWrapper<KeyResultDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("objective_id", objectiveId);
        queryWrapper.eq("deleted", new Byte("0"));
        List<KeyResultDO> keyResultDOS = mapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(keyResultDOS)) {
            keyResultDOS.forEach(x -> {
                x.setDeleted(new Byte("1"));
                mapper.updateById(x);
            });
        }

    }
}
